import torch
import torch.nn as nn


class MyRNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size, num_layers=1):
        """
        :param input_size: 输入的最后一个维度
        :param hidden_size: 隐藏层的最后一个维度
        :param output_size: 最后线性层的输出维度
        :param num_layers: 网络的层数
        """
        super(MyRNN, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.num_layers = num_layers

        # 实例化
        self.rnn = nn.RNN(input_size, hidden_size, num_layers)
        # 实例化全连接线性层
        self.linear = nn.Linear(hidden_size, output_size)
        # 实例化nn中预定义的softmax层,用于从输出层中获得类别的结果
        self.softmax = nn.LogSoftmax(-1)

    def forward(self, input1, hidden):
        """

        :param input1: 输入张量，形状：1 * n_letters
        :param hidden: 隐藏层张量，形状是 self.num_layers * 1 * self.hidden_size
        :return:
        """
        input1 = input1.unsqueeze(0)
        # 1
        rr, hn = self.rnn(input1, hidden)
        return self.softmax(self.linear(rr)), hn

    def init_hidden(self):
        """初始化隐层张量"""
        # 初始化一个（self.num_layers, 1, self.hidden_size）形状的0张量
        return torch.zeros(self.num_layers, 1, self.hidden_size)
